package com.eightbears.beboy.ui.chat.ui.fragment;

import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

import com.easemob.redpacket.utils.RedPacketUtil;
import com.easemob.redpacket.widget.ChatRowRandomPacket;
import com.easemob.redpacket.widget.ChatRowRedPacket;
import com.easemob.redpacket.widget.ChatRowRedPacketAck;
import com.easemob.redpacketsdk.RPSendPacketCallback;
import com.easemob.redpacketsdk.bean.RedPacketInfo;
import com.easemob.redpacketsdk.constant.RPConstant;
import com.easemob.redpacketui.utils.RPRedPacketUtil;
import com.eightbears.beboy.MainActivity;
import com.eightbears.beboy.R;
import com.eightbears.beboy.base.cache.FriendsCache;
import com.eightbears.beboy.base.cache.GroupCache;
import com.eightbears.beboy.base.util.CommonAPI;
import com.eightbears.beboy.base.util.ShowToast;
import com.eightbears.beboy.base.view.popupwindow.BottomSelectionPopup;
import com.eightbears.beboy.base.view.popupwindow.MultipeSelectionPopup;
import com.eightbears.beboy.base.view.record.RecorderActivity;
import com.eightbears.beboy.ui.chat.DemoHelper;
import com.eightbears.beboy.ui.chat.base.domain.EmojiconExampleGroupData;
import com.eightbears.beboy.ui.chat.base.domain.RobotUser;
import com.eightbears.beboy.ui.chat.base.widget.ChatRowVoiceCall;
import com.eightbears.beboy.ui.chat.ui.activity.ForwardMessageActivity;
import com.eightbears.beboy.ui.chat.ui.activity.GroupDetailsActivity;
import com.eightbears.beboy.ui.chat.ui.activity.VideoCallActivity;
import com.eightbears.beboy.ui.chat.ui.activity.VoiceCallActivity;
import com.eightbears.beboy.ui.user.activity.ChatUserInfoActivity;
import com.eightbears.beboy.ui.user.activity.TransferActivity;
import com.eightbears.beboy.ui.user.activity.UserInfoActivity;
import com.eightbears.greendao.Friends;
import com.eightbears.greendao.GroupList;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMCmdMessageBody;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.widget.chatrow.EaseChatRow;
import com.hyphenate.easeui.widget.chatrow.EaseChatRowTransfer;
import com.hyphenate.easeui.widget.chatrow.EaseCustomChatRowProvider;
import com.hyphenate.easeui.widget.emojicon.EaseEmojiconMenu;
import com.hyphenate.exceptions.HyphenateException;
import com.hyphenate.util.EasyUtils;
import com.hyphenate.util.PathUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

import static com.eightbears.beboy.ui.user.activity.UserInfoActivity.PARAMS_USER_INFO;

/**
 * 聊天页面
 */
public class ChatFragment extends EaseChatFragment implements EaseChatFragment.EaseChatFragmentHelper {

    public static final String PARAMS_TO_CHAT_USERNAME = "userName";

    // constant start from 11 to avoid conflict with constant in base class
    private static final int ITEM_VIDEO = 11;
    private static final int ITEM_FILE = 12;
    private static final int ITEM_VOICE_CALL = 13;
    private static final int ITEM_VIDEO_CALL = 14;
    private static final int ITEM_TRANSFER = 15;

    private static final int REQUEST_CODE_SELECT_VIDEO = 11;
    private static final int REQUEST_CODE_SELECT_FILE = 12;
    private static final int REQUEST_CODE_GROUP_DETAIL = 13;
    private static final int REQUEST_CODE_CONTEXT_MENU = 14;
    private static final int REQUEST_CODE_SELECT_AT_USER = 15;
    private static final int REQUEST_CODE_SELECT_TRANSFER = 16;


    private static final int MESSAGE_TYPE_SENT_VOICE_CALL = 1;
    private static final int MESSAGE_TYPE_RECV_VOICE_CALL = 2;
    private static final int MESSAGE_TYPE_SENT_VIDEO_CALL = 3;
    private static final int MESSAGE_TYPE_RECV_VIDEO_CALL = 4;

    //red packet code : 红包功能使用的常量
    private static final int MESSAGE_TYPE_RECV_RED_PACKET = 5;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET = 6;
    private static final int MESSAGE_TYPE_SEND_RED_PACKET_ACK = 7;
    private static final int MESSAGE_TYPE_RECV_RED_PACKET_ACK = 8;
    private static final int MESSAGE_TYPE_RECV_RANDOM = 11;
    private static final int MESSAGE_TYPE_SEND_RANDOM = 12;
    private static final int ITEM_RED_PACKET = 16;


    private static final int MESSAGE_TYPE_SENT_TRANSFER = 1000;
    private static final int MESSAGE_TYPE_RECV_TRANSFER = 1001;


    //end of red packet code
    private Friends mFriends;
    private MultipeSelectionPopup multipeSelectionPopup;
    /**
     * if it is chatBot
     */
    private boolean isRobot;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected void setUpView() {
        setChatFragmentHelper(this);
        if (chatType == CommonAPI.CHATTYPE_SINGLE) {
            Map<String, RobotUser> robotMap = DemoHelper.getInstance().getRobotList();
            if (robotMap != null && robotMap.containsKey(toChatUsername)) {
                isRobot = true;
            }
        }
        super.setUpView();
        mFriends = FriendsCache.getInstance(getActivity()).getCacheById(toChatUsername);
        // set click listener
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (EasyUtils.isSingleActivity(getActivity())) {
                    Intent intent = new Intent(getActivity(), MainActivity.class);
                    startActivity(intent);
                }
                onBackPressed();
            }
        });

        ((EaseEmojiconMenu) inputMenu.getEmojiconMenu()).addEmojiconGroup(EmojiconExampleGroupData.getData());
        if (chatType == EaseConstant.CHATTYPE_GROUP) {
            inputMenu.getPrimaryMenu().getEditText().addTextChangedListener(new TextWatcher() {

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {
//                    if(count == 1 && "@".equals(String.valueOf(s.charAt(start)))){
//                        startActivityForResult(new Intent(getActivity(), PickAtUserActivity.class).
//                                putExtra("groupId", toChatUsername), REQUEST_CODE_SELECT_AT_USER);
//                    }
                }

                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void afterTextChanged(Editable s) {

                }
            });
        }
    }


    @Override
    protected void registerExtendMenuItem() {
        //use the menu in base class
        super.registerExtendMenuItem();
        inputMenu.registerExtendMenuItem(R.string.attach_video, R.mipmap.icon_xiaoshiping, ITEM_VIDEO, extendMenuItemClickListener);
        if (chatType != CommonAPI.CHATTYPE_GROUP) {
            inputMenu.registerExtendMenuItem(R.string.attach_transfer, R.mipmap.icon_transfer, ITEM_TRANSFER, extendMenuItemClickListener);
        }
        if (chatType == CommonAPI.CHATTYPE_SINGLE) {
            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.mipmap.icon_shiping, ITEM_VIDEO_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_voice_call, R.drawable.em_chat_voice_call_selector, ITEM_VOICE_CALL, extendMenuItemClickListener);
//            inputMenu.registerExtendMenuItem(R.string.attach_video_call, R.drawable.em_chat_video_call_selector, ITEM_VIDEO_CALL, extendMenuItemClickListener);
        }
//        if (chatType != CommonAPI.CHATTYPE_CHATROOM) {
//            inputMenu.registerExtendMenuItem(R.string.attach_red_packet, R.drawable.em_chat_red_packet_selector, ITEM_RED_PACKET, extendMenuItemClickListener);
//        }

        // inputMenu.registerExtendMenuItem(R.string.attach_file, R.drawable.em_chat_file_selector, ITEM_FILE, extendMenuItemClickListener);

        //end of red packet code
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SELECT_VIDEO: //send the video
                    if (data != null) {
                        int duration = data.getIntExtra("dur", 0);
                        String videoPath = data.getStringExtra("path");
                        File file = new File(PathUtil.getInstance().getImagePath(), "thvideo" + System.currentTimeMillis());
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            Bitmap ThumbBitmap = ThumbnailUtils.createVideoThumbnail(videoPath, 3);
                            ThumbBitmap.compress(CompressFormat.JPEG, 100, fos);
                            fos.close();
                            sendVideoMessage(videoPath, file.getAbsolutePath(), duration);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_FILE: //send the file
                    if (data != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            sendFileByUri(uri);
                        }
                    }
                    break;
                case REQUEST_CODE_SELECT_AT_USER:
                    if (data != null) {
                        String username = data.getStringExtra("username");
                        inputAtUsername(username, false);
                    }
                    break;


                case REQUEST_CODE_SELECT_TRANSFER://send the transfer
                    if (data != null) {
                        String transfer_amount = data.getStringExtra("transfer_amount");
                        String cover = data.getStringExtra("cover");
                        sendTransferMessage(transfer_amount, cover);
                    }


                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onSetMessageAttributes(EMMessage message) {
        if (isRobot) {
            //set message extension
            message.setAttribute("em_robot_message", isRobot);
        }
    }

    @Override
    public EaseCustomChatRowProvider onSetCustomChatRowProvider() {
        return new CustomChatRowProvider();
    }


    @Override
    public void onEnterToChatDetails() {
        if (chatType == CommonAPI.CHATTYPE_GROUP) {
            EMGroup group = EMClient.getInstance().groupManager().getGroup(toChatUsername);
            if (group == null) {
                Toast.makeText(getActivity(), R.string.gorup_not_found, Toast.LENGTH_SHORT).show();
                return;
            }
            startActivityForResult((new Intent(getActivity(), GroupDetailsActivity.class)
                    .putExtra("groupId", toChatUsername).putExtra(CommonAPI.EXTAR_POSITION, position)), REQUEST_CODE_GROUP_DETAIL);
            getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
        }
    }

    @Override
    public void onEnterUserInfoDetails(String toChatUser, int position) {
        Intent intent = new Intent(getActivity(), ChatUserInfoActivity.class);
        intent.putExtra(PARAMS_TO_CHAT_USERNAME, toChatUser);
        intent.putExtra(EaseConstant.EXTAR_POSITION, position);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    public void onAvatarClick(String username) {
        //handling when user click avatar
        Intent intent = new Intent(getActivity(), UserInfoActivity.class);
        intent.putExtra(PARAMS_USER_INFO, username);
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    public void onAvatarLongClick(String username) {
        inputAtUsername(username);
    }


    @Override
    public boolean onMessageBubbleClick(EMMessage message) {
        //消息框点击事件，demo这里不做覆盖，如需覆盖，return true
        //red packet code : 拆红包页面
        if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
            RedPacketUtil.openRedPacket(getActivity(), chatType, message, toChatUsername, messageList);
            return true;
        }
        //end of red packet code
        return false;
    }

    @Override
    public void onCmdMessageReceived(List<EMMessage> messages) {
        //red packet code : 处理红包回执透传消息
        for (EMMessage message : messages) {
            EMCmdMessageBody cmdMsgBody = (EMCmdMessageBody) message.getBody();
            String action = cmdMsgBody.action();//获取自定义action
            if (action.equals(RPConstant.REFRESH_GROUP_RED_PACKET_ACTION)) {
                RedPacketUtil.receiveRedPacketAckMessage(message);
                messageList.refresh();
            }
        }
        //end of red packet code
        super.onCmdMessageReceived(messages);
    }

    @Override
    public void onMessageBubbleLongClick(EMMessage message) {

        String trans = message.getStringAttribute(CommonAPI.transferType, null);

        int type = message.getType().ordinal();
        multipeSelectionPopup = new MultipeSelectionPopup(getActivity());
        if (type == EMMessage.Type.TXT.ordinal()) {

            if (message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_VIDEO_CALL, false)
                    || message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_VOICE_CALL, false)
                    //red packet code : 屏蔽红包消息的转发功能
                    || message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
                multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
            } else if (message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_BIG_EXPRESSION, false)) {
                multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
                multipeSelectionPopup.setTx_3Text(getString(R.string.forward));
            } else if (trans != null)
                multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
            else {
                multipeSelectionPopup.setTx_1Text(getString(R.string.copy_message));
                multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
                multipeSelectionPopup.setTx_3Text(getString(R.string.forward));
            }
        } else if (type == EMMessage.Type.LOCATION.ordinal()) {
            multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
        } else if (type == EMMessage.Type.IMAGE.ordinal()) {
            multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
            multipeSelectionPopup.setTx_3Text(getString(R.string.forward));
        } else if (type == EMMessage.Type.VOICE.ordinal()) {
            multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
        } else if (type == EMMessage.Type.VIDEO.ordinal()) {
            multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
        } else if (type == EMMessage.Type.FILE.ordinal()) {
            multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
        }

        if (chatType == EaseConstant.CHATTYPE_CHATROOM
                //red packet code : 屏蔽红包消息的撤回功能
                || message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
            multipeSelectionPopup.setTx_1Text(getString(R.string.copy_message));
            multipeSelectionPopup.setTx_2Text(getString(R.string.delete_message));
        }

        multipeSelectionPopup.setOnClickItemListener(new MultipeSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        clipboard.setPrimaryClip(ClipData.newPlainText(null, ((EMTextMessageBody) contextMenuMessage.getBody()).getMessage()));
                        break;
                    case R.id.ll_2:
                        conversation.removeMessage(contextMenuMessage.getMsgId());
                        messageList.refresh();
                        break;
                    case R.id.ll_3:
                        Intent intent = new Intent(getActivity(), ForwardMessageActivity.class);
                        intent.putExtra("forward_msg_id", contextMenuMessage.getMsgId());
                        startActivity(intent);
                        getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                        break;
                }
                multipeSelectionPopup.dismiss();
            }
        });
        multipeSelectionPopup.showPopupWindow();
    }

    @Override
    public boolean onExtendMenuItemClick(int itemId, View view) {
        switch (itemId) {
            case ITEM_VIDEO:
                Intent intent = new Intent(getActivity(), RecorderActivity.class);
                startActivityForResult(intent, REQUEST_CODE_SELECT_VIDEO);
                getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
            case ITEM_FILE: //file
                selectFileFromLocal();
                break;
            case ITEM_VOICE_CALL:
            case ITEM_VIDEO_CALL:
                if (mFriends == null) ShowToast.showShortToast("对方不是您的好友, 无法通话");
                else startCall();
                break;
            //red packet code : 进入发红包页面
            case ITEM_RED_PACKET:
                //注意：不再支持原有的startActivityForResult进入红包相关页面
                int itemType;
                if (chatType == EaseConstant.CHATTYPE_SINGLE) {
                    itemType = RPConstant.RP_ITEM_TYPE_SINGLE;
                    //小额随机红包
                    //itemType = RPConstant.RP_ITEM_TYPE_RANDOM;
                } else {
                    itemType = RPConstant.RP_ITEM_TYPE_GROUP;
                }
                RedPacketUtil.startRedPacket(getActivity(), itemType, toChatUsername, new RPSendPacketCallback() {
                    @Override
                    public void onGenerateRedPacketId(String redPacketId) {

                    }

                    @Override
                    public void onSendPacketSuccess(RedPacketInfo redPacketInfo) {
                        sendMessage(RedPacketUtil.createRPMessage(getActivity(), redPacketInfo, toChatUsername));
                    }
                });
                break;
            case ITEM_TRANSFER:
                Intent intent1 = new Intent(getActivity(), TransferActivity.class);
                startActivityForResult(intent1.putExtra("username", toChatUsername)
                        .putExtra("cover", mFriends.getCover())
                        .putExtra("nickname", mFriends.getNickname())
                        .putExtra("userId", mFriends.getUser_id()), REQUEST_CODE_SELECT_TRANSFER);
                getActivity().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
                break;
            //end of red packet code
            default:
                break;
        }
        //keep exist extend menu
        return false;
    }

    /**
     * select file
     */
    protected void selectFileFromLocal() {
        Intent intent = null;
        if (Build.VERSION.SDK_INT < 19) { //api 19 and later, we can't use this way, demo just select from images
            intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);

        } else {
            intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        }
        startActivityForResult(intent, REQUEST_CODE_SELECT_FILE);
    }


    /**
     * make a video call
     */
    protected void startCall() {

        final BottomSelectionPopup selectionPopup = new BottomSelectionPopup(getActivity());
        selectionPopup.setTx_1Text("语音通话");
        selectionPopup.setTx_2Text("视频通话");
        selectionPopup.setTxCancel("取消");
        selectionPopup.setOnClickItemListener(new BottomSelectionPopup.OnClicktemListener() {
            @Override
            public void onClickItem(View v) {
                switch (v.getId()) {
                    case R.id.ll_1:
                        if (!EMClient.getInstance().isConnected()) {
                            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
                        } else {
                            startActivity(new Intent(getActivity(), VoiceCallActivity.class).putExtra("username", toChatUsername)
                                    .putExtra("cover", mFriends.getCover())
                                    .putExtra("nickname", mFriends.getNickname())
                                    .putExtra("isComingCall", false));
                            // voiceCallBtn.setEnabled(false);
                            inputMenu.hideExtendMenuContainer();
                        }
                        break;
                    case R.id.ll_2:
                        if (!EMClient.getInstance().isConnected())
                            Toast.makeText(getActivity(), R.string.not_connect_to_server, Toast.LENGTH_SHORT).show();
                        else {
                            startActivity(new Intent(getActivity(), VideoCallActivity.class).putExtra("username", toChatUsername)
                                    .putExtra("cover", mFriends.getCover())
                                    .putExtra("nickname", mFriends.getNickname())
                                    .putExtra("isComingCall", false));
                            // videoCallBtn.setEnabled(false);
                            inputMenu.hideExtendMenuContainer();
                        }
                        break;
                    default:

                        break;
                }
                selectionPopup.dismiss();
            }
        });
        selectionPopup.showPopupWindow();

    }

    /**
     * chat row provider
     */
    private final class CustomChatRowProvider implements EaseCustomChatRowProvider {
        @Override
        public int getCustomChatRowTypeCount() {
            //here the number is the message type in EMMessage::Type
            //which is used to count the number of different chat row
            return 10;
        }

        @Override
        public int getCustomChatRowType(EMMessage message) {
            if (message.getType() == EMMessage.Type.TXT) {
                //voice call
                if (message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_VOICE_CALL, false)) {
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VOICE_CALL : MESSAGE_TYPE_SENT_VOICE_CALL;
                } else if (message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    //video call
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_VIDEO_CALL : MESSAGE_TYPE_SENT_VIDEO_CALL;
                }
                //red packet code : 红包消息、红包回执消息以及转账消息的chatrow type
                else if (RedPacketUtil.isRandomRedPacket(message)) {
                    //小额随机红包
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RANDOM : MESSAGE_TYPE_SEND_RANDOM;
                } else if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {
                    //发送红包消息
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET : MESSAGE_TYPE_SEND_RED_PACKET;
                } else if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {
                    //领取红包消息
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_RED_PACKET_ACK : MESSAGE_TYPE_SEND_RED_PACKET_ACK;
                } else if (message.getBooleanAttribute(String.valueOf(DemoHelper.getInstance().isTransferTxtMessage(message)), false)) {
                    return message.direct() == EMMessage.Direct.RECEIVE ? MESSAGE_TYPE_RECV_TRANSFER : MESSAGE_TYPE_SENT_TRANSFER;
                }
                //end of red packet code
            }
            return 0;
        }

        @Override
        public EaseChatRow getCustomChatRow(EMMessage message, int position, BaseAdapter adapter) {
            if (message.getType() == EMMessage.Type.TXT) {
                // voice call or video call
                if (message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_VOICE_CALL, false) ||
                        message.getBooleanAttribute(CommonAPI.MESSAGE_ATTR_IS_VIDEO_CALL, false)) {
                    return new ChatRowVoiceCall(getActivity(), message, position, adapter);
                } else if (DemoHelper.getInstance().isTransferTxtMessage(message)) {
                    return new EaseChatRowTransfer(getActivity(), message, position, adapter);
                }
                //red packet code : 红包消息、红包回执消息以及转账消息的chat row
                else if (RedPacketUtil.isRandomRedPacket(message)) {//小额随机红包
                    return new ChatRowRandomPacket(getActivity(), message, position, adapter);
                } else if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_MESSAGE, false)) {//红包消息
                    return new ChatRowRedPacket(getActivity(), message, position, adapter);
                } else if (message.getBooleanAttribute(RPConstant.MESSAGE_ATTR_IS_RED_PACKET_ACK_MESSAGE, false)) {//红包回执消息
                    return new ChatRowRedPacketAck(getActivity(), message, position, adapter);
                }
                //end of red packet code
            }
            return null;
        }

    }

    Handler groupUpdate = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                titleBar.setTitle(String.valueOf(msg.obj));
            }
        }
    };

    public void updateTitle(final String title) {
        Message message = new Message();
        message.what = 1;
        message.obj = title;
        groupUpdate.sendMessage(message);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onDataSynEvent(String event) {
        switch (event) {
            case GroupDetailsActivity.EVENT_GROUP_UPDATE:
                GroupList group = GroupCache.getInstance(getContext()).getCacheById(toChatUsername);
                updateTitle(group.getGroupname());
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //调用该方法可防止红包SDK引起的内存泄漏
        RPRedPacketUtil.getInstance().detachView();
        EventBus.getDefault().unregister(this);
    }


}
